package org.fund.framework.config;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.*;

/**
 * @Author:
 * @Date: 2022/3/24 14:37
 * @Description:
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //获取当前机器的核数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        taskRegistrar.setScheduler(getExecutor(cpuNum,cpuNum*2,300));
    }
    /**
     * 获取线程池
     *
     * @param corePoolSize     最小线程数
     * @param maxPoolSize      最大线程数
     * @param keepAliveSeconds 允许空闲时间(秒)
     * @return 返回队列
     */
    protected ScheduledExecutorService getExecutor(int corePoolSize, int maxPoolSize, long keepAliveSeconds) {
        //线程名称
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNamePrefix("schedule-pool-%d").build();
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
        //最小线程数
        executor.setCorePoolSize(corePoolSize);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //最大线程数
        executor.setMaximumPoolSize(maxPoolSize);
        //允许空闲时间(秒)
        executor.setKeepAliveTime(keepAliveSeconds, TimeUnit.SECONDS);
        return executor;
    }
}
